﻿using HandyControl.Data;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace YY.Admin.Core.Converter
{
    /// <summary>
    /// 根据 TitleWidth 计算 Margin.Left，如果 TitlePlacement=Top 则不偏移
    /// </summary>
    public class NegativeLeftThicknessConverter : IMultiValueConverter
    {
        // 这里改成 MultiBinding，方便同时拿 TitleWidth 和 TitlePlacement
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            double left = 0;
            double bottomShift = -18;

            if (parameter != null && double.TryParse(parameter.ToString(), out var p))
                bottomShift = p;

            // 🛑 如果 TitleWidth 还未设置，直接返回默认 Thickness
            if (values.Length > 0 && values[0] != DependencyProperty.UnsetValue)
            {
                var widthValue = values[0];
                if (widthValue is GridLength gridLength && gridLength.IsAbsolute)
                    left = gridLength.Value;
                else if (widthValue is double d)
                    left = d;
            }

            // 🛑 如果 TitlePlacement 还未设置，也要避免异常
            if (values.Length > 1 && values[1] != DependencyProperty.UnsetValue)
            {
                if (values[1] is TitlePlacementType placement)
                {
                    // 如果标题在上方，则不偏移
                    if (placement == TitlePlacementType.Top)
                        left = 0;
                }
            }

            return new Thickness(left, 0, 0, bottomShift);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
            => throw new NotSupportedException();
    }
}
